<?

include('/var/www/endeepen/tpb/xml.php');

#configure the daylife api server url here
$daylife_server = "freepi.daylife.com";
$protocol = "jsonrest";
$version = "4.5";
$publicapi_access_url = "http://" . $daylife_server . "/" . $protocol . "/publicapi/" . $version . "/";

$topic_page_name = "topic"; 
$stories_page_name = "stories";
$images_page_name = "images";
$related_topics_page_name = "related_topics";
$quotes_page_name  = "quotes";

#Input params
$topic_name = (isset($_GET['name'])) ? $_GET['name'] : 'Central Intelligence Agency';
$topic_id = (isset($_GET['topic_id'])) ? $_GET['topic_id'] : '';
$end_time = (isset($_GET['end_time'])) ? $_GET['end_time'] : time();
$start_time  = (isset($_GET['start_time'])) ? $_GET['start_time'] : $end_time - (31 * 86400);

$sort = (isset($_GET['sort'])) ? $_GET['sort'] : 'date';
$offset = (isset($_GET['offset'])) ? $_GET['offset'] : 0;
$limit = (isset($_GET['limit'])) ? $_GET['limit'] : 5;


//Donovan added  to get the config from the server url
$SERVER_NAME = $_SERVER["SERVER_NAME"];
list($config_instance) = split("[/.]", $SERVER_NAME, 2);

//echo $SERVER_NAME . " | " . $config_instance;

$base_config_dir = "/var/www/endeepen/instances/";

$instance_config_path = $base_config_dir . $config_instance . "/instance_config.xml";

$instance_theme_path = $base_config_dir . $config_instance . "/theme/";

$current_theme_template = $base_config_dir . $config_instance . "/theme/topic.tpl";

$check_for_config = file_exists($instance_config_path);

$xml_config = $instance_config_path;

$config_custom_parts_path = "/var/www/endeepen/instances/" . $config_instance . "/parts/";

$xml_config_data = file_get_contents($xml_config);

$dom = new DomDocument();
$dom->loadXML($xml_config_data);

//$dom->validate('config.xsd');
#configure your api credentials here
$accesskey = $dom->getElementsByTagName('accesskey')->item(0)->textContent;;
$sharedsecret = $dom->getElementsByTagName('sharedsecret')->item(0)->textContent;;


$custom_header_html = $dom->getElementsByTagName('header_html')->item(0)->textContent;
$footer_html  = $dom->getElementsByTagName('footer_html')->item(0)->textContent;

//Adding logic to pull theme from config.

$theme = $dom->getElementsByTagName('theme')->item(0)->textContent;
$theme = trim($theme);

if ($theme == "")
    {
    $theme = "smarty/templates/index.tpl";
    }

$css_includes = $dom->getElementsByTagName('css_includes')->item(0)->textContent;

//$topic_template_id = $dom->getElementsByTagName('canned_style')->item(0)->textContent;


$include_images = $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('enabled')->item(0)->textContent;
$sort_images    = $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('sort')->item(0)->textContent;
$limit_images       = (isset($_GET['limit'])) ? $_GET['limit'] : $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('limit')->item(0)->textContent;
$filter_id_images       = $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('source_filter_id')->item(0)->textContent;
$include_publication_images = $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('include_publication_images')->item(0)->textContent;
$end_time_images = $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('end_time')->length ? $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('end_time')->item(0)->textContent: time();
$start_time_images = $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('start_time')->length ? $dom->getElementsByTagName('images')->item(0)->getElementsByTagName('start_time')->item(0)->textContent: $end_time - (31 * 86400) ;
/*
$include_articles     = $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('enabled')->item(0)->textContent;
$sort_articles	      = $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('sort')->item(0)->textContent; 
$limit_articles	      = (isset($_GET['limit'])) ? $_GET['limit'] : $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('limit')->item(0)->textContent;
$include_image_articles = $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('include_image')->item(0)->textContent;
$include_scores_articles = $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('include_scores')->item(0)->textContent;
$end_time_articles = $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('end_time')->length ? $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('end_time')->item(0)->textContent: time();
$start_time_articles = $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('start_time')->length ? $dom->getElementsByTagName('articles')->item(0)->getElementsByTagName('start_time')->item(0)->textContent: $end_time - (31 * 86400) ;
*/

$include_stories     = $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('enabled')->item(0)->textContent;
$sort_stories	      = $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('sort')->item(0)->textContent; 
$limit_stories	      = (isset($_GET['limit'])) ? $_GET['limit'] : $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('limit')->item(0)->textContent;
$include_image_stories = $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('include_image')->item(0)->textContent;
$include_scores_stories = $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('include_scores')->item(0)->textContent;
$end_time_stories = $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('end_time')->length ? $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('end_time')->item(0)->textContent: time();
$start_time_stories = $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('start_time')->length ? $dom->getElementsByTagName('stories')->item(0)->getElementsByTagName('start_time')->item(0)->textContent: $end_time - (31 * 86400) ;



$include_quotes	      = $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('enabled')->item(0)->textContent;
$sort_quotes	      = $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('sort')->item(0)->textContent; 
$limit_quotes	      = (isset($_GET['limit'])) ? $_GET['limit'] : $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('limit')->item(0)->textContent;
$include_image_quotes = $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('include_image')->item(0)->textContent;
$speakers_quotes = $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('speakers')->item(0)->textContent;
$end_time_quotes = $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('end_time')->length ? $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('end_time')->item(0)->textContent: time();
$start_time_quotes = $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('start_time')->length ? $dom->getElementsByTagName('quotes')->item(0)->getElementsByTagName('start_time')->item(0)->textContent: $end_time - (31 * 86400) ;

$include_connections  = $dom->getElementsByTagName('connections')->item(0)->getElementsByTagName('enabled')->item(0)->textContent;
$sort_connections	      = $dom->getElementsByTagName('connections')->item(0)->getElementsByTagName('sort')->item(0)->textContent; 
$limit_connections	      = (isset($_GET['limit'])) ? $_GET['limit'] : $dom->getElementsByTagName('connections')->item(0)->getElementsByTagName('limit')->item(0)->textContent;
$include_image_connections    = 1; //$dom->getElementsByTagName('connections')->item(0)->getElementsByTagName('include_image')->item(0)->textContent;

$include_topic_types_connections = $dom->getElementsByTagName('include_topic_types');

$topic_type_connections = $include_topic_types_connections->item(0)->getElementsByTagName('topic_type');
$include_topic_type_connections = $topic_type_connections->length ? $topic_type_connections->item(0)->textContent : "";

for ($i = 1; $i < $topic_type_connections->length; $i++){
   $include_topic_type_connections .= ",".$topic_type_connections->item(1)->textContent;
}

if ($include_topic_type_connections == "") $include_topic_type_connections = "person,place,organization";

$end_time_connections = $dom->getElementsByTagName('connections')->item(0)->getElementsByTagName('end_time')->length ? $dom->getElementsByTagName('connections')->item(0)->getElementsByTagName('end_time')->item(0)->textContent: time();
$start_time_connections = $dom->getElementsByTagName('connections')->item(0)->getElementsByTagName('start_time')->length ? $dom->getElementsByTagName('connections')->item(0)->getElementsByTagName('start_time')->item(0)->textContent: $end_time - (31 * 86400) ;

$topic_info = topic_getInfo($topic_name, $topic_id);
$isTopic = ($topic_info !== NULL) ? true : false;


//Sloppy handling of admin mode.
//TODO: Make sure we're logged in to enter admin mode, and ensure that you can only edit YOUR pages.

if(isset($_GET['adminmode']))
{
        session_start();
        $_SESSION['adminmode'] = $_GET['adminmode'];
}

class Properties {
    protected $xml_file;
    protected $properties;

    public function __construct($xml_file) {
        $this->properties = $this->readPropertiesFromXML($xml_file);
        #print_r($this->properties);
        $this->xml_file = $xml_file;
    }

    public function readPropertiesFromXML($xml_file) {
        $data = file_get_contents($xml_file);
        return XML_unserialize($data);
    }

    public function getProperties() {
        return $this->properties;
    }

    public function writePropertiesXML() {
        print_r($this->properties);
        $xml = XML_serialize($this->properties);
        file_put_contents($this->xml_file, $xml);
    }

    public function updateProperties($properties) {
        $this->properties = $properties;
        $this->writePropertiesXML();
    }

}


function full_copy( $source, $target )
    {
        if ( is_dir( $source ) )
        {
            @mkdir( $target );
           
            $d = dir( $source );
           
            while ( FALSE !== ( $entry = $d->read() ) )
            {
                if ( $entry == '.' || $entry == '..' )
                {
                    continue;
                }
               
                $Entry = $source . '/' . $entry;           
                if ( is_dir( $Entry ) )
                {
                    full_copy( $Entry, $target . '/' . $entry );
                    continue;
                }
                copy( $Entry, $target . '/' . $entry );
            }
           
            $d->close();
        }else
        {
            copy( $source, $target );
        }
    }

function topic_getInfo($topic_name, $topic_id) {
    global $sharedsecret, $accesskey, $publicapi_access_url;

    #get handle to public api
    $publicapi = new PublicApi($publicapi_access_url, $accesskey, $sharedsecret);

    #build params for article search
    $params = array();
    if (isset($topic_name)) $params['name'] = $topic_name;
    else if (isset($topic_id)) $params['topic_id'] = $topic_id;
    $params['include_image'] = 1;
    $params['include_wikipedia_info'] = 1;
    

    #make the API call
    $results = $publicapi->topic_getInfo($params);

    #check for response and error codes
    if ((isset($results['response']['code']))
            && ($results['response']['code'] > 0)
            && (isset($results['response']['payload']['topic'])))
        return $results['response']['payload']['topic'];
    else
        return NULL;
}


function topic_getRelatedStories($topic_name, $topic_id, $start_time, $end_time, $sort, $offset, $limit, $include_scores) {
    global $sharedsecret, $accesskey, $publicapi_access_url,$isTopic;

    #get handle to public api
    $publicapi = new PublicApi($publicapi_access_url, $accesskey, $sharedsecret);

    #build params for article search
    $params = array();
    
    if (isset($start_time)) $params['start_time'] = $start_time;
    if (isset($end_time)) $params['end_time'] = $end_time;
    if (isset($sort)) $params['sort'] = $sort;
    if (isset($offset)) $params['offset'] = $offset;
    if (isset($limit)) $params['limit'] = $limit;
    if (isset($include_scores)) $params['include_scores'] = $include_scores;

    #make the API call
    if ($isTopic) {
    	if (isset($topic_name)) $params['name'] = $topic_name;
    	else if (isset($topic_id)) $params['topic_id'] = $topic_id;
    
    	$results = $publicapi->topic_getRelatedStories($params);
    	
    	    #check for response and error codes
	    if ((isset($results['response']['code']))
	            && ($results['response']['code'] > 0)
	            && (isset($results['response']['payload']['story'])))
	        return $results['response']['payload']['story'];
	    else
	        return array();
	    	
    }
    else {
    	$params['query'] = $topic_name;
    	$results = $publicapi->search_getRelatedArticles($params);
    	
    	    #check for response and error codes
	    if ((isset($results['response']['code']))
	            && ($results['response']['code'] > 0)
	            && (isset($results['response']['payload']['article'])))
	        return $results['response']['payload']['article'];
	    else
	        return array();
	    	
    }

}

function get_theme_form (){
    $themedir="/var/www/endeepen/themes/";
    $themearray = array();
    
    if ($handle = opendir($themedir)) {

        while (false !== ($file = readdir($handle))) {
            array_push($themearray, $file);
        }
    
    closedir($handle);
    
    sort($themearray);
    
    $theme_base_dir = "/var/www/endeepen/themes/";

    $themeform = "<form method='POST'  action='". $_SERVER['PHP_SELF'] . "'> \n <table>";
    
    foreach ($themearray as $theme)
        {
            if ($theme != "." && $theme != "..")
            {
             
                $themeform .= "<tr>";
                $themeform .= "<td><input type='radio' name='theme' value='" . $theme . "'></td>";
                $themeform .= "<td><img src='/themes/" . $theme . "/thumb.png' ></td>";          
                $theme_config_path = $theme_base_dir . $theme . "/topic.xml";   
                $properties_reader = new Properties($theme_config_path);   
                $properties = $properties_reader->getProperties();
                $theme_info = $properties['theme_config']['theme_basics'];
                $theme_name = $theme_info['theme_name'];
                $theme_description = $theme_info['theme_description'];
                $author = $theme_info['author'];
                $author_email = $theme_info['author_email'];
                
                $themeform .= "<td>";
                $themeform .= "<b>" . $theme_name . "</b><br />";
                $themeform .= "<i>by <a href='mailto:" . $author_email . "'>". $author . "</a></i><br />";
                $themeform .= $theme_description;
                $themeform .= "<input type='hidden' name='_submit_check' value='1'/>";
                $themeform .= "</td>";
                
                $themeform .= "</tr>";    
            }
        }
    
    
        $themeform .= "</table><input type='submit' value='save theme configuration'></form> \n";
    
    return $themeform;
    }
}




function get_customized_styles() {
    $SERVER_NAME = $_SERVER["SERVER_NAME"];
    list($config_instance) = split("[/.]", $SERVER_NAME, 2);
    
    //echo $SERVER_NAME . " | " . $config_instance;
    
    $base_config_dir = "/var/www/endeepen/instances/";
    
    $instance_path = $base_config_dir . $config_instance . "/" .  $config_instance. ".xml";
    
    $theme_customization_path = $base_config_dir . $config_instance . "/theme/topic.xml";
    
    $check_for_config = file_exists($theme_customization_path);

    $working_customizations = "<!-- no customization found -->";


    if ($check_for_config){
        
        $working_customizations = "<style> \n <!-- \n";        
        $xml_config_data = file_get_contents($theme_customization_path);               
        $customization_xml = new SimpleXMLElement($xml_config_data);       
        $custom_styles = $customization_xml->styles;
        
        
              //Add Type Treatments
        $type_treatments = $custom_styles->type_treatments;       
        
        foreach ($type_treatments->children() as $typestyle)
        {
           $thestyle = "";
           $thestyle .= "." . $typestyle->getName() . "{" . "\n";
           
           foreach ($typestyle->children() as $stylelement){
                $thestyle .= $stylelement->getName() . ":";
                $thestyle .= $stylelement . "; \n";
           }
           $thestyle .= "} \n";
           $working_customizations .= $thestyle;
        }

        //Add Boxes and Colors
        
        $boxesandcolor_treatments = $custom_styles->boxesandcolors;
        
        
        
        foreach ($boxesandcolor_treatments->children() as $bandcstyles)
        {
           $thestyle = "";
           $thestyle = "." . $bandcstyles->getName() . "{" . "\n";
           
           foreach ($bandcstyles->children() as $stylelement){
                $thestyle .= $stylelement->getName() . ":";
                $thestyle .= $stylelement . "; \n";
           }
           $thestyle .= "} \n";
           $working_customizations .= $thestyle;
        }
        
        

        
        $working_customizations .= "--></style>";
        
        


    }
    
    return $working_customizations;
  
}



function topic_getRelatedImages($topic_name, $topic_id, $start_time, $end_time, $sort, $offset, $limit, $include_publication_images, $source_filter_id) {
    global $sharedsecret, $accesskey, $publicapi_access_url,$isTopic;

    #get handle to public api
    $publicapi = new PublicApi($publicapi_access_url, $accesskey, $sharedsecret);

    #build params for article search
    $params = array();
    if (isset($start_time)) $params['start_time'] = $start_time;
    if (isset($end_time)) $params['end_time'] = $end_time;
    if (isset($sort)) $params['sort'] = $sort;
    if (isset($offset)) $params['offset'] = $offset;
    if (isset($limit)) $params['limit'] = $limit;
    if (isset($include_publication_images)) $params['include_publication_images'] = $include_publication_images;
    if (isset($source_filter_id)) $params['source_filter_id'] = $source_filter_id;

    #make the API call
    if ($isTopic) {
    	if (isset($topic_name)) $params['name'] = $topic_name;
    	else if (isset($topic_id)) $params['topic_id'] = $topic_id;
    
    	$results = $publicapi->topic_getRelatedImages($params);
    }
    else {
    	$params['query'] = $topic_name;
    	$results = $publicapi->search_getRelatedImages($params);
    }
    
    #check for response and error codes
    if ((isset($results['response']['code']))
            && ($results['response']['code'] > 0)
            && (isset($results['response']['payload']['image'])))
	{
        	return $results['response']['payload']['image'];
	}
    else
    {
        return array();
    }
}


function topic_getRelatedTopics($topic_name, $topic_id, $start_time, $end_time, $sort, $offset, $limit,  $include_topic_type, $include_image) {
    global $sharedsecret, $accesskey, $publicapi_access_url,$isTopic;

    #get handle to public api
    $publicapi = new PublicApi($publicapi_access_url, $accesskey, $sharedsecret);

    #build params for article search
    $params = array();
    if (isset($start_time)) $params['start_time'] = $start_time;
    if (isset($end_time)) $params['end_time'] = $end_time;
    if (isset($sort)) $params['sort'] = $sort;
    if (isset($offset)) $params['offset'] = $offset;
    if (isset($limit)) $params['limit'] = $limit;
    if (isset($include_topic_type)) $params['include_topic_type'] = $include_topic_type;
    if (isset($include_image)) $params['include_image'] = 1; //$include_image;

    #make the API call
    if ($isTopic) {
    	if (isset($topic_name)) $params['name'] = $topic_name;
    	else if (isset($topic_id)) $params['topic_id'] = $topic_id;
    
    	$results = $publicapi->topic_getRelatedTopics($params);
    }
    else {
    	$params['query'] = $topic_name;
    	$results = $publicapi->search_getRelatedTopics($params);
    }
    

    #check for response and error codes
    if ((isset($results['response']['code']))
            && ($results['response']['code'] > 0)
            && (isset($results['response']['payload']['topic'])))
        return $results['response']['payload']['topic'];
    else
        return array();
}


function topic_getRelatedQuotes($topic_name, $topic_id, $start_time, $end_time, $sort, $offset, $limit) {
    global $sharedsecret, $accesskey, $publicapi_access_url,$isTopic;

    #get handle to public api
    $publicapi = new PublicApi($publicapi_access_url, $accesskey, $sharedsecret);

    #build params for article search
    $params = array();
    if (isset($start_time)) $params['start_time'] = $start_time;
    if (isset($end_time)) $params['end_time'] = $end_time;
    if (isset($sort)) $params['sort'] = $sort;
    if (isset($offset)) $params['offset'] = $offset;
    if (isset($limit)) $params['limit'] = $limit;

    #make the API call
    if ($isTopic) {
    	if (isset($topic_name)) $params['name'] = $topic_name;
    	else if (isset($topic_id)) $params['topic_id'] = $topic_id;
    
    	$results = $publicapi->topic_getRelatedQuotes($params);
    }
    else {
    	$params['query'] = $topic_name;
    	$results = $publicapi->search_getRelatedQuotes($params);
    }

    #check for response and error codes
    if ((isset($results['response']['code']))
            && ($results['response']['code'] > 0)
            && (isset($results['response']['payload']['quote'])))
        return $results['response']['payload']['quote'];
    else
        return array();
}



function print_newline( $num )
{
	for($num; $num>0; $num--)
		echo "<br>";
}

function print_log( $str )
{
	print_newline(1);
	echo "LOG::";
	echo $str;
	print_newline(1);
}

function get_link_html($page_name, $link_name, $params){
  // whichever link matches the page name, give it a separate field
  if ($page_name == $link_name) {
    return '<A class="searchBy selected"
	  href="'.$link_name.'.php?'.params_encode($params).'">
'.$link_name.'</A>';
  } else {
    return '<A class="searchBy"
	  href="'.$link_name.'.php?'.params_encode($params).'">'.$link_name.'</A>';
  }
}

function get_sort_html($sort_used, $sort_option, $page_name, $params){
  if ($sort_option == $sort_used){
    return '<A class="sortBy selected"
	  href="'.$page_name.'.php?'.params_encode($params).'">'.$sort_option.'</A>';
  } else {
    $params['sort'] = $sort_option;
    return '<A class="sortBy"
	href="'.$page_name.'.php?'.params_encode($params).'">'.$sort_option.'</A>';
  }
}


function params_encode($params){
  $str = '';
  foreach ((array)$params as $k => $v){
	  $str.= urlencode($k);
	  $str.= '=';
	  $str.= urlencode($v);
	  $str .= '&';
  }
  return $str;
}

function get_links_html($page_name, $sort_used){
  // get the links
  global $topic_page_name, $stories_page_name,  $images_page_name, $related_topics_page_name, $quotes_page_name;

  global $params;
  $hlinkparams = $params;

  #Although limit for topic page is 5, links to other pages should have a limit of 10.
  $hlinkparams['limit'] = 10;

  $links_html = '<DIV id="searchByContainer">
	  View :&nbsp;';
  
  $links_html .= get_link_html($page_name, $topic_page_name, $hlinkparams);
  $links_html .= '&nbsp;|&nbsp;';
  $links_html .= get_link_html($page_name, $stories_page_name, $hlinkparams);
  $links_html .= '&nbsp;|&nbsp;';
  $links_html .= get_link_html($page_name, $images_page_name, $hlinkparams);
  $links_html .= '&nbsp;|&nbsp;';
  $links_html .= get_link_html($page_name, $related_topics_page_name, $hlinkparams);
  $links_html .= '&nbsp;|&nbsp;';
  $links_html .= get_link_html($page_name, $quotes_page_name, $hlinkparams);
  $links_html .= '&nbsp;|&nbsp;';

  $links_html .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $links_html .= 'Sort By :&nbsp;';

  $links_html .= get_sort_html($sort_used, "date", $page_name, $hlinkparams);
  $links_html .= '&nbsp;|&nbsp;';
  $links_html .= get_sort_html($sort_used, "relevance", $page_name, $hlinkparams);

  return $links_html;
}

function get_info_html($info){
  $str = '';
  foreach($info as $topic) {
	  $str .=  '<h1> '.$topic['name'].' ('.$topic['type'].')</h1>';
  }
  return $str;
}


function get_stories_html($stories){
  $str = '';
  $str .= '<div id="stories">';
  $str .=  '<h2 class="story_header">Related Stories</h2>';
  foreach($stories as $story) {
    $single_story_html = '';
    $single_story_html .= '<div class="story">';
    $single_story_html .= '<h3 class="story_headline><a href="'.$story['url'].'">'.$story['headline'].'</a></h3>';
    if (isset($story['scores']) && isset($story['scores']['newsdomain']))
      {
         $single_story_html .= '<div class="newsdomain">Category: '.$story['scores']['newsdomain'].'</div>';
       }
    $single_story_html .= '<div class="story_excerpt">'.$story['excerpt'].'</div>';
    $single_story_html .= '<div class="story_published">Published on <text class="timestamp">'.date("Y-m-d H:i:s", $story['timestamp_epoch']).'</text> by <a class="source" href="'.$story['source']['url'].'">'.$story['source']['name'].'</a></div>';
    $single_story_html .= '</div>';
    $str .= $single_story_html;
  }
  //END STORIES
  $str .= '</div>';
  return $str;
}


function get_images_html($images) {
  $str = '';
  $str .= '<div id="images">';
  $str .= '<h2>Related Images</h2>';
  foreach($images as $image) {
    $single_image_html = '';

    $single_image_html .= '<div class="image"><td><a href="'.$image['url'].'"><img src= "'.$image['thumb_url'].'"></img></a></div>';
 //   $single_image_html .= '<tr class="image_source"><td> Source: <a href="'.$image['source']['url'].'">'.$image['source']['name'].'</a></td></tr>';
    $single_image_html .= '<div class="image_pub"> Published on <text class="timestamp">'.date("Y-m-d H:i:s", $image['timestamp_epoch']).'</text> by <a class="source" href="'.$image['source']['url'].'">'.$image['source']['name'].'</a></div>';
    $single_image_html .= '</div>';
    $str .= $single_image_html;
  }
  $str .= '</div>';
  return $str;
}

function get_related_topics_html($topics) {
  $str = '';
  $str .= '<div id="related_topics">';
  $str .=  '<h2>Related Topics</h2>';

  foreach($topics as $topic) {
    $single_topic_html = '';
    # add new row for each topic
    $single_topic_html .= '<div class="topic">';
    # add new cell for the image
    $single_topic_html .= '<div class="topic-image">';
    $image_url = "/images/s_default.jpg";
    //print_r($topic);
    if (isset($topic['image'])) {
      $image_url = $topic['image'][0]['thumb_url'];
    }
    $single_topic_html .= '<img src= "'.$image_url.'"></img>';
    $single_topic_html .= '</div>';
    #done with image, now add link
    $single_topic_html .= '<div class="related_topic_name">';
    $single_topic_html .= '<a href="'.$topic['name'].'">'.$topic['name'].' ('.$topic['type'].')</a>';
    $single_topic_html .= '</div>';
    $single_topic_html .= '</div>';
    $str .=  $single_topic_html;
  }
  $str .= '</div>';
  return $str;
}

function get_quotes_html($quotes) {
  $str = '';
  $str .= '<div id="quotes">';
  $str .=  '<h2>Quotes</h2>';
  $num_quotes = count($quotes);
  
  if ($num_quotes > 0){
    foreach($quotes as $quote) {
      $single_quote_html = '';
      $single_quote_html .= '<div class="quote">';
      $single_quote_html .= '<a href="'.$quote['url'].'">'.$quote['quote_text'].'<a>';
      $single_quote_html .= '</div>';
      $quote_source   = $quote['name'];
      if ($quote_source == ""){
        $quote_source = '';
      }
      else
      {
      $single_quote_html .= '<div class="quote-source"> -- '.$quote_source.'';
      }
      $single_article_html = '%ARTICLE_HEADLINE% published on %ARTICLE_TIMESTAMP% by %ARTICLE_SOURCE_NAME%';
      $article_html = $single_article_html;
      $article_html = str_replace("%ARTICLE_URL%", $quote['article']['url'], $article_html);
      $article_html = str_replace("%ARTICLE_HEADLINE%", $quote['article']['headline'], $article_html);
      $article_html = str_replace("%ARTICLE_TIMESTAMP%", date("Y-m-d H:i:s",$quote['article']['timestamp_epoch']), $article_html);
      $article_html = str_replace("%ARTICLE_SOURCE_NAME%", $quote['source']['name'], $article_html);
      $article_html = str_replace("%ARTICLE_SOURCE_URL%", $quote['source']['url'], $article_html);

      $single_quote_html .=  '<div class="quote_article">'.$article_html.'</div>';
      $str .= $single_quote_html;
    }
    $str .= '</div>';
  }
  return $str;
}

function get_header($info, $stories, $images, $topics, $quotes){
   global $header_html, $footer_html, $css_includes, $topic_template_id;
   $header_html = '<html><head>';
   if ($topic_template_id > 0)
      {
         $inserthtml = '<style type="text/css">@import url(/media/topic_' . trim($topic_template_id) . '.css);</style>';
         $header_html .= $inserthtml;
      }
   else
      {
          $header_html .= '<style type="text/css">@import url(/media/topic.css);</style>';
      }
      
   if(strstr($css_includes,"http"))
      {
       $inserthtml = '<style type="text/css">@import url(' . trim($css_includes) . ');</style>';
       $header_html .= $inserthtml;
      }
   $header_html .= '<link rel="stylesheet" type="text/css" href="/media/subModal.css" />';
   $header_html .= '<script type="text/javascript" src="/media/common.js">';
   $header_html .= '<script type="text/javascript" src="/media/subModal.js">';
   $header_html .='</head>';
   return $header_html;
}

function get_footer($info, $stories, $images, $topics, $quotes){
 global $footer_html;
 
 if(strstr($footer_html,"http")){
   $inserthtml = file_get_contents($footer_html);
 }
 
 $inserthtml .= '</body></html>';
 return $inserthtml;
}




function get_admin_layer(){
	global $admin_html;
	$admin_html = file_get_contents("/var/www/endeepen/tpb/admin_cpanel.html");
        $admin_html = str_replace("%currentPage%", $_SERVER['PHP_SELF'], $admin_html);
	return $admin_html;
	
}

function insert_admin_layer($compiled, &$smarty)
{
    //this needs to be a more robust insertion 
    if(isset($_SESSION['adminmode']))
		{
		$adminmode = $_SESSION['adminmode'];
		}
	else
		{
		$adminmode = 0;
		}
    
    if($adminmode){
        $admin_cpanel = get_admin_layer();
        $cpanel_insert = "<body>" . $admin_cpanel;
        $compiled = str_ireplace("<body>", $cpanel_insert , $compiled);
    }
    return $compiled;
    
}

function insert_custom_styles($compiled, &$smarty){
   //TODO: this needs to be a more robust insertion
   $customized_styles = get_customized_styles();
   $customized_styles_insert = $customized_styles . "\n </head";
   $compiled = str_ireplace("</head", $customized_styles_insert , $compiled);
   return $compiled;       
}

function insert_dynamic_page_items($compiled, &$smarty)
{
    global $config_instance;
    global $config_custom_parts_path;
    
    
    $custom_css_path = $config_custom_parts_path . "styles.css";
    $custom_css_href = "/instances/" . $config_instance . "/parts/styles.css";
    
    
    $header_html = "";
    
    if (file_exists($custom_css_path))
    {
        $header_html .= '<link rel="stylesheet" type="text/css" href="' . $custom_css_href . '" />';
    }



   $header_html .= '<link rel="stylesheet" type="text/css" href="/instances/' . $config_instance . '/theme/topic.css" />';
   $header_html .= '<link rel="stylesheet" type="text/css" href="/media/subModal.css" />';
   $header_html .= '<script type="text/javascript" src="/media/common.js">';
   $header_html .= '<script type="text/javascript" src="/media/subModal.js">';
   
    //TODO: this needs to be a more robust insertion   
    $header_insert = "<head>" . $header_html;
    $compiled = str_ireplace("<head>", $header_insert , $compiled);
    
    $footer_html = file_get_contents("/var/www/endeepen/tpb/tpb_footer.html");
    $footer_html .= "\n </body>";
    $compiled = str_ireplace("</body>", $footer_html , $compiled);
    
    return $compiled;
}

function renderHTML($info, $stories, $images, $topics, $quotes) {

  $header = get_header($info, $stories, $images, $topics, $quotes);
  $body   = get_body($info, $stories, $images, $topics, $quotes);
  $footer = get_footer($info, $stories, $images, $topics, $quotes);
  $html = $header.$body.$footer;
  echo $html;
}


function get_custom_header(){
   
    global $config_instance;
    global $config_custom_parts_path;
    
    
    $custom_header_path = $config_custom_parts_path . "header.html";
    $default_header_path = "/var/www/endeepen/instances/" . $config_instance . "/theme/parts/header.html";
    
    $custom_header = "";
    
    if (file_exists($custom_header_path))
    {
        $custom_header .= file_get_contents($custom_header_path);
    }
    else{
        if (file_exists($default_header_path))
        {
        $custom_header .= file_get_contents($default_header_path);
        }
        
    }
        
   return $custom_header;
}

function get_custom_footer(){
    global $config_instance;
    global $config_custom_parts_path;
    
    
    $custom_footer_path = $config_custom_parts_path . "footer.html";
    $default_footer_path = "/var/www/endeepen/instances/" . $config_instance . "/theme/parts/footer.html";
    
    $custom_footer = "";
    
    if (file_exists($custom_footer_path))
    {
        $custom_footer .= file_get_contents($custom_footer_path);
    }
    else{
        if (file_exists($default_footer_path))
        {
        $custom_footer .= file_get_contents($default_footer_path);
        }
        
    }
        
   return $custom_footer;
}

function get_custom_css_content(){
    global $config_instance;
    global $config_custom_parts_path;
    
    
    $custom_css_path = $config_custom_parts_path . "styles.css";
    $default_css_path = "/var/www/endeepen/instances/" . $config_instance . "/theme/parts/styles.css";
    
    $custom_css = "";
    
    if (file_exists($custom_css_path))
    {
        $custom_css .= file_get_contents($custom_css_path);
    }
    else{
        if (file_exists($default_css_path))
        {
        $custom_css .= file_get_contents($default_css_path);
        }
        
    }
        
   return $custom_css;
}

function get_custom_css(){
    global $css_includes;
    $custom_css = "";
    if(strstr($css_includes,"http")){
      $custom_css = '<style type="text/css">@import url(' . trim($css_includes) . ');</style>';
    }
   return $custom_css;
}


function get_body($info, $stories, $images, $topics, $quotes){

  global $custom_header_html;
  


  
  $body = '<body>';
  
  // Conditionally add admin cpanel
	if(isset($_SESSION['adminmode']))
		{
		$adminmode = $_SESSION['adminmode'];
		}
	else
		{
		$adminmode = 0;
		}

	if ($adminmode)
		$body .= get_admin_layer();
  
  $body .= '<div id="page_area">';
   if(strstr($custom_header_html,"http")){
      $body .= file_get_contents($custom_header_html);
   }
  //$body .= get_links_html("topic", $sort);
 
  $body .= '<div id="content">';

  if ($info) {
    $body .= get_info_html($info); 
  }

  if ($stories) {
    $body .= get_stories_html($stories);
  }

  if ($images) {
    $body .= get_images_html($images);
  }

  if ($topics) {
    $body .= get_related_topics_html($topics);
  }

  if ($quotes) {
    $body .= get_quotes_html($quotes);
}

  $body .= '</div></div>';
  return $body;
}

class JsonDatasource {

    var $json_datasource_url = null;
    var $encoding_hook = null;

    public function __construct($json_datasource_url, $encoding_hook=null) {
        $this->json_datasource_url = $json_datasource_url;
        if (!$encoding_hook) {
        	$encoding_hook = new DefaultEncodingHook();
        }
        $this->encoding_hook = $encoding_hook;
    }


    /**
     * Magic method to invoke an json server method.
     */
    public function __call($call, $args=array()) {
    	if(count($args) != 0) {
    		$args=$args[0];
    	}
		$file = $this->constructUrl($call, $args);
        #echo "<a href=\"$file\">$file</a><br>";
		$json = file_get_contents($file);

		return json_decode($json, true);
    }
    
	public function constructUrl($action, $params) {
		$url = $this->json_datasource_url . $action;
		$query = html_entity_decode($this->query_string_encode($params,null));
		//print($url . '?' . $query . "\n");
		return $url . '?' . $query;
	}
	
	public function query_string_encode($data, $key) {
	    $ret = array();
	    foreach ((array)$data as $k => $v) {
			if(!empty($key)) {
				$k = $key;
      		}
			if (is_array($v) || is_object($v)) {
				array_push($ret, $this->query_string_encode($v,$k));
			} else if (isset($v)) {
    			$this->encoding_hook->encode($k, $v, &$ret);
	    	}
		}	
		$sep = ini_get('arg_separator.output');
	   	return implode($sep, $ret);
	}

    private function get_microsecs() {
		$time = gettimeofday(true);
		$seconds = $time['sec'];
		$micros = $time['usec'];
		return $seconds . "." . $micros;
    }
}

class DefaultEncodingHook {
	public function encode($k, $v, $ret) {
		array_push($ret, urlencode($k).'='.urlencode($v));
	}
}

class PublicApiEncodingHook {

    var $access_key = null;
    var $shared_secret = null;
    var $id_params = array("topic_id", "quote_id", "image_id", "article_id", "source_id");
    var $name_params = array("query", "name");

    public function __construct($access_key, $shared_secret) {
        $this->access_key = $access_key;
        $this->shared_secret = $shared_secret;
    }

    public function encode($k, $v, $ret) {
        $is_id = false;
        $is_name = false;
        if ($is_id = in_array($k, $this->id_params) || $is_name = in_array($k, $this->name_params)) {
            if ($is_id && is_numeric($v)) {
                $v = encode_id($v);
            }
            $signature = md5($this->access_key . $this->shared_secret . $v);
            array_push($ret, urlencode("signature").'='.urlencode($signature));
            array_push($ret, urlencode("accesskey").'='.urlencode($this->access_key));
        }
        array_push($ret, urlencode($k).'='.urlencode($v));
    }
}

class PublicApi extends JsonDatasource {
    public function __construct($json_datasource_url, $access_key, $shared_secret) {
        parent::__construct($json_datasource_url, new PublicApiEncodingHook($access_key, $shared_secret));
    }
}


?>

